package net.lesscoding.shop.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import net.lesscoding.shop.common.Result;
import net.lesscoding.shop.entity.User;
import net.lesscoding.shop.entity.UserMoneyLog;
import net.lesscoding.shop.enums.ShopCode;
import net.lesscoding.shop.exception.CastException;
import net.lesscoding.shop.mapper.UserMapper;
import net.lesscoding.shop.mapper.UserMoneyLogMapper;
import net.lesscoding.shop.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.Objects;

/**
 * @author 24962
 * @description 针对表【trade_user】的数据库操作Service实现
 * @createDate 2024-06-07 15:16:06
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
        implements UserService {
    @Autowired
    private UserMapper userMapper;

    @Autowired
    private UserMoneyLogMapper moneyLogMapper;

    @Override
    public Result updateUserMoney(UserMoneyLog userMoneyLog) {
        if (userMoneyLog == null ||
                userMoneyLog.getUserId() == null ||
                userMoneyLog.getOrderId() == null) {
            CastException.cast(ShopCode.SHOP_REQUEST_PARAMETER_VALID);
        }
        UserMoneyLog lastLog = moneyLogMapper.selectOne(new QueryWrapper<UserMoneyLog>()
                .eq("order_id", userMoneyLog.getOrderId())
                .eq("user_id", userMoneyLog.getUserId())
                .eq("money_log_type", userMoneyLog.getMoneyLogType())
                .last("order by create_time desc limit 1")
        );
        User user = userMapper.selectById(userMoneyLog.getUserId());
        // 扣款
        if (Objects.equals(userMoneyLog.getMoneyLogType(), ShopCode.SHOP_USER_MONEY_PAID.getCode())) {
            if (lastLog != null) {
                CastException.cast(ShopCode.SHOP_ORDER_PAY_STATUS_IS_PAY);
            }
            user.setUserMoney(user.getUserMoney().subtract(userMoneyLog.getUseMoney()));
            userMapper.updateById(user);
        }
        // 退款
        if (Objects.equals(userMoneyLog.getMoneyLogType(), ShopCode.SHOP_USER_MONEY_REFUND.getCode())) {
            if (lastLog != null) {
                CastException.cast(ShopCode.SHOP_USER_MONEY_REFUND_ALREADY);
            }
            user.setUserMoney(user.getUserMoney().add(userMoneyLog.getUseMoney()));
            userMapper.updateById(user);
        }
        userMoneyLog.setCreateTime(LocalDateTime.now());
        moneyLogMapper.insert(userMoneyLog);
        return Result.success(true);
    }
}




